var koa = require('koa');
var app = new koa();
var Router = require('koa-router');
var createLogger = require('concurrency-logger').default;
const session = require('koa-session');
const {koaBody} = require('koa-body');
const koaStatic = require('koa-static');

var router = new Router();
const logger = createLogger({});

app.keys = ['some_secret_hurr'];

const CONFIG = {
  key: 'koa-sess', /** (string) cookie key (default is koa:sess) */
  /** (number || 'session') maxAge in ms (default is 1 days) */
  /** 'session' will result in a cookie that expires when session/browser is closed */
  /** Warning: If a session cookie is stolen, this cookie will never expire */
  maxAge: 86400000,
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
};

router.get('/api/products', (ctx, next) => {
	ctx.body = [{
    name:'xhh',
    images:['/xxx']
  }]
});

router.post('/login', (ctx, next) => {
	ctx.session.userinfo = ctx.request.body;
	console.log("req body ---->", ctx.request.body);
	ctx.body = {msg: 'login success'}
});

router.post('/login-test', (ctx, next) => {
	console.log("login test @@", {userinfo: ctx.session.userinfo});
	ctx.body = {msg:'yes',userinfo: ctx.session.userinfo}
});

let port = 1338

app
  .use(koaStatic('./static'))
  .use(koaBody())
  .use(session(CONFIG, app))
  .use(router.routes())
  .use(router.allowedMethods())
  .use(logger)
  .listen(port);

console.log(`server listen ${port} ########`);
